import React, { useState, useEffect } from 'react';
import { Button, Table, Select, Space, Alert, message, Modal, Form, Input, Switch } from 'antd';
import { ApiOutlined, ReloadOutlined, EditOutlined, DatabaseOutlined } from '@ant-design/icons';
import { request } from '@umijs/max';
import type { ColumnsType } from 'antd/es/table';

interface DataSourceTable {
  name: string;
  comment?: string;
  row_count?: number;
}

interface DataSourceTablesResponse {
  tables: DataSourceTable[];
  total_count: number;
}

interface DataSourceField {
  id: number;
  name: string;
  display_name: string;
  field_type: string;
  description?: string;
  is_primary: boolean;
  is_nullable: boolean;
  is_email: boolean;
  is_name: boolean;
  sample_value?: string;
  data_format?: string;
}

interface DataSourceFieldManagerProps {
  dataSourceId: number;
  dataSourceType: string;
}

const DataSourceFieldManager: React.FC<DataSourceFieldManagerProps> = ({
  dataSourceId,
  dataSourceType,
}) => {
  const [tables, setTables] = useState<DataSourceTable[]>([]);
  const [selectedTable, setSelectedTable] = useState<string>('');
  const [fields, setFields] = useState<DataSourceField[]>([]);
  const [tablesLoading, setTablesLoading] = useState(false);
  const [fieldsLoading, setFieldsLoading] = useState(false);
  const [analyzeLoading, setAnalyzeLoading] = useState(false);
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editingField, setEditingField] = useState<DataSourceField | null>(null);
  const [form] = Form.useForm();

  // 获取表列表
  const fetchTables = async () => {
    if (dataSourceType === 'CSV') {
      // CSV文件没有表的概念
      setSelectedTable('csv_data');
      return;
    }

    setTablesLoading(true);
    try {
      const response: DataSourceTablesResponse = await request(
        `/api/data-sources/${dataSourceId}/tables`,
        {
          method: 'GET',
        }
      );
      setTables(response.tables);
      if (response.tables.length > 0) {
        setSelectedTable(response.tables[0].name);
      }
    } catch (error: any) {
      message.error(error.message || '获取表列表失败');
    } finally {
      setTablesLoading(false);
    }
  };

  // 获取字段列表
  const fetchFields = async () => {
    setFieldsLoading(true);
    try {
      const response = await request(`/api/data-sources/${dataSourceId}/fields`, {
        method: 'GET',
      });
      setFields(response || []);
    } catch (error: any) {
      message.error(error.message || '获取字段列表失败');
    } finally {
      setFieldsLoading(false);
    }
  };

  // 分析字段
  const handleAnalyzeFields = async () => {
    if (!selectedTable && dataSourceType !== 'CSV') {
      message.warning('请先选择要分析的表');
      return;
    }

    setAnalyzeLoading(true);
    try {
      const params: any = {};
      if (selectedTable && dataSourceType !== 'CSV') {
        params.table_name = selectedTable;
      }

      await request(`/api/data-sources/${dataSourceId}/analyze-fields`, {
        method: 'POST',
        params,
      });
      
      message.success('字段分析完成');
      fetchFields(); // 重新获取字段列表
    } catch (error: any) {
      message.error(error.message || '字段分析失败');
    } finally {
      setAnalyzeLoading(false);
    }
  };

  // 编辑字段
  const handleEditField = (field: DataSourceField) => {
    setEditingField(field);
    form.setFieldsValue({
      display_name: field.display_name,
      description: field.description,
      is_email: field.is_email,
      is_name: field.is_name,
    });
    setEditModalVisible(true);
  };

  // 保存字段编辑
  const handleSaveField = async () => {
    if (!editingField) return;

    try {
      const values = await form.validateFields();
      await request(`/api/data-sources/${dataSourceId}/fields/${editingField.id}`, {
        method: 'PUT',
        data: values,
      });
      
      message.success('字段更新成功');
      setEditModalVisible(false);
      fetchFields(); // 重新获取字段列表
    } catch (error: any) {
      message.error(error.message || '字段更新失败');
    }
  };

  useEffect(() => {
    fetchTables();
    fetchFields();
  }, [dataSourceId, dataSourceType]);

  // 表格列定义
  const columns: ColumnsType<DataSourceField> = [
    {
      title: '字段名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      render: (text: string) => <strong>{text}</strong>,
    },
    {
      title: '类型',
      dataIndex: 'field_type',
      key: 'field_type',
      width: 80,
      render: (type: string) => {
        const typeMap: Record<string, string> = {
          string: '文本',
          number: '数字',
          date: '日期',
          boolean: '布尔',
          email: '邮箱',
        };
        return typeMap[type] || type;
      },
    },
    {
      title: '属性',
      key: 'attributes',
      width: 120,
      render: (_, record) => (
        <Space size={4} wrap>
          {record.is_primary && <span style={{ color: '#1890ff', fontSize: '12px' }}>主键</span>}
          {!record.is_nullable && <span style={{ color: '#52c41a', fontSize: '12px' }}>必填</span>}
          {record.is_email && <span style={{ color: '#fa8c16', fontSize: '12px' }}>邮箱</span>}
          {record.is_name && <span style={{ color: '#722ed1', fontSize: '12px' }}>姓名</span>}
        </Space>
      ),
    },
    {
      title: '样例值',
      dataIndex: 'sample_value',
      key: 'sample_value',
      width: 100,
      render: (text: string) => text || '-',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      render: (text: string) => text || '-',
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Button
          type="link"
          size="small"
          icon={<EditOutlined />}
          onClick={() => handleEditField(record)}
        >
          编辑
        </Button>
      ),
    },
  ];

  return (
    <div>
      <Space direction="vertical" style={{ width: '100%' }}>
        {/* 表选择器 */}
        {dataSourceType !== 'CSV' && (
          <div>
            <Space>
              <DatabaseOutlined />
              <span>选择表：</span>
              <Select
                style={{ width: 200 }}
                placeholder="请选择表"
                value={selectedTable}
                onChange={setSelectedTable}
                loading={tablesLoading}
                options={tables.map(table => ({
                  label: (
                    <div>
                      <div>{table.name}</div>
                      {table.comment && (
                        <div style={{ fontSize: '12px', color: '#666' }}>
                          {table.comment}
                        </div>
                      )}
                      {table.row_count !== null && (
                        <div style={{ fontSize: '12px', color: '#999' }}>
                          约 {table.row_count} 行
                        </div>
                      )}
                    </div>
                  ),
                  value: table.name,
                }))}
              />
            </Space>
          </div>
        )}

        {/* 操作按钮 */}
        <div>
          <Space>
            <Button
              type="primary"
              icon={<ApiOutlined />}
              onClick={handleAnalyzeFields}
              loading={analyzeLoading}
              disabled={!selectedTable && dataSourceType !== 'CSV'}
            >
              分析字段
            </Button>
            <Button
              icon={<ReloadOutlined />}
              onClick={fetchFields}
              loading={fieldsLoading}
            >
              刷新
            </Button>
          </Space>
        </div>

        {/* 字段表格 */}
        <Table
          columns={columns}
          dataSource={fields}
          rowKey="id"
          loading={fieldsLoading}
          pagination={false}
          size="small"
          locale={{ emptyText: '暂无字段数据，请点击"分析字段"按钮' }}
        />
      </Space>

      {/* 编辑字段模态框 */}
      <Modal
        title="编辑字段"
        open={editModalVisible}
        onOk={handleSaveField}
        onCancel={() => setEditModalVisible(false)}
        width={500}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            label="显示名称"
            name="display_name"
            rules={[{ required: true, message: '请输入显示名称' }]}
          >
            <Input placeholder="请输入字段显示名称" />
          </Form.Item>
          
          <Form.Item label="描述" name="description">
            <Input.TextArea placeholder="请输入字段描述" rows={3} />
          </Form.Item>
          
          <Form.Item label="字段属性">
            <Space direction="vertical">
              <Form.Item name="is_email" valuePropName="checked" noStyle>
                <Switch size="small" /> 邮箱字段
              </Form.Item>
              <Form.Item name="is_name" valuePropName="checked" noStyle>
                <Switch size="small" /> 姓名字段
              </Form.Item>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DataSourceFieldManager;
